<template>
  <div class="book-manage">
    <!-- 顶部操作区域 -->
    <div class="toolbar">
      <h2 class="section-title">图书列表</h2>
      <div class="search-bar">
        <input v-model="searchKeyword" type="text" placeholder="请输入书名" />
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="book-table-wrapper">
      <table class="book-table">
        <thead>
          <tr>
            <th>书名</th>
            <th>作者</th>
            <th class="fixed-width">价格</th>
            <th>库存</th>
            <th class="action-column">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="book in filteredBooks" :key="book.id">
            <td>{{ book.name }}</td>
            <td>{{ book.author }}</td>

            <!-- 价格列：可编辑状态 -->
            <td class="fixed-width">
              <div v-if="editingBookId === book.id">
                <input type="number" v-model="editPriceValue" class="price-input" />
              </div>
              <div v-else>
                {{ book.price }}
              </div>
            </td>

            <td>{{ book.stock }}</td>

            <!-- 操作列 -->
            <td class="action-column">
              <div class="action-buttons">
                <div v-if="editingBookId === book.id">
                  <button @click="submitPrice(book)" class="blue-btn">提交</button>
                </div>
                <div v-else>
                  <button @click="startEditPrice(book)" class="blue-btn">修改价格</button>
                </div>

                <button @click="toggleStatus(book)" class="blue-btn">
                  {{ book.status === 0 ? '下架' : '上架' }}
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-if="isLoading" class="loading-indicator">加载中...</div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

// Book 接口定义
interface Book {
  id: number
  name: string
  author: string
  price: number
  stock: number
  status: number
}

// --- 1. 编辑价格逻辑 ---

// 当前正在编辑价格的图书ID
const editingBookId = ref<number | null>(null)

// 编辑框中输入的价格
const editPriceValue = ref<number>(0)

// 点击“修改价格”时触发，初始化输入框并切换为编辑状态
function startEditPrice(book: Book) {
  editingBookId.value = book.id // 记录当前编辑的图书ID
  editPriceValue.value = book.price // 把当前图书价格填进输入框
}

// 点击“提交”时触发，请求后端更新价格
async function submitPrice(book: Book) {
  const payload = {
    id: book.id,
    price: editPriceValue.value, // 传当前输入的价格
  }

  try {
    const response = await axios.put('/api/Book/updatePrice', payload)

    console.log('后端响应:', response.data)

    // 根据后端返回格式判断是否成功（假设返回 { success: true }）
    if (response.data.success) {
      book.price = editPriceValue.value // 本地更新图书价格
      editingBookId.value = null // 退出编辑状态
    } else {
      console.warn('更新失败：', response.data.message || '未知错误')
    }
  } catch (error) {
    console.error('请求出错:', error)
  }
}

// --- 2. 上下架逻辑 ---
async function toggleStatus(book: Book) {
  const newStatus = book.status === 0 ? 1 : 0

  // 要发送的数据
  const payload = {
    id: book.id,
    status: newStatus,
  }

  // 打印发送的数据
  console.log('发送数据:', payload)

  try {
    const response = await axios.put('/api/Book/updateStatus', payload)

    // 打印响应结果
    console.log('后端响应:', response.data)

    if (response.data.success) {
      book.status = newStatus
    } else {
      console.warn('状态更新失败：', response.data.message || '未知错误')
    }
  } catch (error) {
    console.error('请求出错:', error)
  }
}

// --- 3. 搜索与加载 ---
const searchKeyword = ref('')
const isLoading = ref(false)
const books = ref<Book[]>([])

onMounted(async () => {
  isLoading.value = true
  try {
    const response = await axios.get('/api/Book/all')
    books.value = response.data // 假设后端直接返回 Book[] 数组
  } catch (error) {
    console.error('加载图书失败：', error)
  } finally {
    isLoading.value = false
  }
})

// 响应式搜索过滤
const filteredBooks = computed(() =>
  books.value.filter((book) =>
    book.name.toLowerCase().includes(searchKeyword.value.trim().toLowerCase()),
  ),
)
</script>

<style scoped>
.section-title {
  font-size: 20px;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 5px;
}

.book-manage {
  padding-right: 20px;
  padding-left: 20px;
}

.book-table-wrapper {
  max-height: 620px;
  overflow-y: auto;
  margin-bottom: 20px;
  border: 1px solid #ccc;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
}

.search-bar input {
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.book-table {
  width: 100%;
  border-collapse: collapse;
}

.book-table th,
.book-table td {
  border: 1px solid #ccc;
  padding: 12px;
  text-align: left;
}

.book-table th {
  background-color: #f5f5f5;
}

/* 固定价格列宽 */
.fixed-width {
  width: 120px;
  min-width: 120px;
}

.price-input {
  width: 100%;
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

/* 操作列样式 */
.action-column {
  width: 250px;
  min-width: 200px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: space-between;
  flex-wrap: wrap;
}

.blue-btn {
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  min-width: 100px;
}

.blue-btn:hover {
  background-color: #409eff;
}

.loading-indicator {
  text-align: center;
  color: #888;
  margin-top: 20px;
}
</style>
